package tw.org.iii.mysocketclientsample;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class ActMain extends Activity {
	String strDeviceId="QK";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actmain);
		InitialComponent();
		
		StrictMode.ThreadPolicy l_policy = 
			new StrictMode.ThreadPolicy.Builder().permitAll().build();
	 StrictMode.setThreadPolicy( l_policy);
		
	}
	
	private void SendTo(String strFrom,String strTo,String strMessagte) {
		try {
			Socket remote =new Socket("192.168.1.161",1022);
			DataOutputStream streamOut= 
					new DataOutputStream(remote.getOutputStream());
			streamOut.writeUTF(
					strFrom+"\t"+
					strTo+"\t"+
					strMessagte+".");				
			
			DataInputStream streamIn=
					new DataInputStream(remote.getInputStream());
			String s=streamIn.readUTF();
			lblMessage.setText(s);
			remote.close();
			
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	OnClickListener btnAdd_click=new OnClickListener(){
		public void onClick(View arg0) {
		
			
			SendTo(
					strDeviceId,
					txtTo.getText().toString(),
					txtSend.getText().toString()					
					);
			
			Toast.makeText(ActMain.this, "送出資料成功", Toast.LENGTH_SHORT).show();
			txtSend.setText("");
	}

		};
	
	
	OnClickListener btnBrowse_click=new OnClickListener(){
		public void onClick(View arg0) {
			
			SendTo(
					strDeviceId,
					txtTo.getText().toString(),
					""
					);


	}};
	
	private void InitialComponent() {
		
		btnAdd=(Button)findViewById(R.id.btnAdd);
		btnAdd.setOnClickListener(btnAdd_click);
		btnBrowse=(Button)findViewById(R.id.btnBrowse);
		btnBrowse.setOnClickListener(btnBrowse_click);
		txtSend=(EditText)findViewById(R.id.txtSend);
		txtTo=(EditText)findViewById(R.id.txtTo);
		lblMessage=(TextView)findViewById(R.id.lblMessage);
	}
   
	Button btnAdd=null;
	Button btnBrowse=null;
	EditText txtSend=null;
	EditText txtTo=null;

	TextView lblMessage=null;
}
